<template>
  <div class="play-type" ref="tabBar">
    <span ref="tabs"
      v-for="(game, index) in data"
      :class="currentPlayTypeIndex === index ? 'active-play' : ''"
      @click="selectPlayType(game, index)"
      :key="index"
      >{{ game.playTypeName }}</span
    >
  </div>
</template>

<script>
export default {
  name: "sub-game-nav",
  props: {
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
        currentPlayTypeIndex: 0, //当前的索引
    };
  },
  methods: {
    selectPlayType(game, index) {
       this.currentPlayTypeIndex = index;
       this.$emit("selectPlayType", index);
        // 获取标签栏容器的 DOM 元素
        const tabBarElement = this.$refs.tabBar;

        // 获取要滚动的标签元素
        const targetTabElement = this.$refs.tabs[index];

        // 计算所有标签的总宽度
        const totalTabsWidth = Array.from(tabBarElement.children).reduce((width, tab) => {
        return width + tab.clientWidth;
        }, 0);

        // 计算滚动的距离，使目标标签滚动到容器的中央
        const scrollOffset = targetTabElement.offsetLeft - (tabBarElement.clientWidth - targetTabElement.clientWidth) / 2;

        // 计算滚动的最大距离，以确保不超出标签栏的边界
        const maxScrollOffset = totalTabsWidth - tabBarElement.clientWidth;

        // 使用 scrollLeft 属性滚动标签栏，并确保在边界内滚动
        tabBarElement.scrollLeft = Math.max(0, Math.min(maxScrollOffset, scrollOffset));

    },
  },
};
</script>

<style scoped lang="less">
.play-type {
  display: flex;        
  justify-content: flex-start; 
  align-items: stretch; 
  white-space:nowrap;
  overflow-y: auto;

  span {
    flex-shrink: 0; 
    color: #c17070;
    border: 1px solid #efc1c1;
    border-radius: 10px;
    font-size: 12px;
    width: 60px;
    height: 24px;
    margin-right: 5px;
    margin-top: 5px;
    line-height: 24px;
    text-align: center;
  }

  .active-play {
    background: linear-gradient(180deg, #f77e7e 0%, #f33b3b 100%);
    color: white;
    border: 1px solid white;
  }
}
</style>
